import React, { Component } from 'react';
import { connect } from 'react-redux';
import { 
  List, 
  SearchBar, 
  PullToRefresh, 
  Empty,
  Button,
  Toast,
  Space,
  Avatar
} from 'antd-mobile';
import { 
  SearchOutline, 
  ExclamationCircleOutline,
  UnorderedListOutline,
  UserOutline
} from 'antd-mobile-icons';
import { 
  fetchPlayers, 
  searchPlayers, 
  sortPlayers,
  setSearchTerm, 
  setSort,
  clearSearch,
  clearSort
} from '../../store/reducers/playerSlice';
import styles from './PlayerList.module.less';

class PlayerList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      refreshing: false,
      showSort: false,
    };
  }

  componentDidMount() {
    this.loadPlayers();
  }

  loadPlayers = () => {
    const { dispatch } = this.props;
    dispatch(fetchPlayers());
  };

  handleSearch = (value) => {
    const { dispatch } = this.props;
    dispatch(setSearchTerm(value));
    
    if (value.trim()) {
      dispatch(searchPlayers(value));
    } else {
      dispatch(fetchPlayers());
    }
  };

  handleClearSearch = () => {
    const { dispatch } = this.props;
    dispatch(clearSearch());
    dispatch(fetchPlayers());
  };

  handleSort = (sortType, sortOrder) => {
    const { dispatch } = this.props;
    dispatch(setSort({ type: sortType, order: sortOrder }));
    dispatch(sortPlayers({ sortType, sortOrder }));
    this.setState({ showSort: false });
  };

  handleClearSort = () => {
    const { dispatch } = this.props;
    dispatch(clearSort());
    dispatch(fetchPlayers());
  };

  handleRefresh = async () => {
    this.setState({ refreshing: true });
    try {
      await this.loadPlayers();
    } finally {
      this.setState({ refreshing: false });
    }
  };

  handlePlayerClick = (player) => {
    Toast.show(`点击了球员: ${player.name} (${player.number}号)`);
    // 这里可以跳转到球员详情页或显示详情弹窗
  };

  handleRetry = () => {
    this.loadPlayers();
  };

  getPlayerAvatar = (player) => {
    // 这里可以根据球员ID生成头像URL，或者使用默认头像
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${player.name}`;
  };

  renderPlayerItem = (player) => {
    return (
      <List.Item
        key={player.id}
        onClick={() => this.handlePlayerClick(player)}
        className={styles.playerItem}
      >
        <div className={styles.playerContent}>
          {/* 球员头像 */}
          <div className={styles.playerAvatar}>
            <Avatar
              src={this.getPlayerAvatar(player)}
              style={{ '--size': '50px' }}
              className={styles.avatar}
            />
          </div>

          {/* 球员信息 */}
          <div className={styles.playerInfo}>
            <div className={styles.playerName}>{player.name}</div>
            <div className={styles.playerDetails}>
              <UserOutline className={styles.detailIcon} />
              <span>球员</span>
            </div>
          </div>

          {/* 球员号码 */}
          <div className={styles.playerNumber}>
            <div className={styles.numberDisplay}>
              {player.number}
            </div>
            <div className={styles.numberLabel}>号</div>
          </div>
        </div>
      </List.Item>
    );
  };

  renderSortBar = () => {
    const { showSort } = this.state;
    
    if (!showSort) return null;

    return (
      <div className={styles.sortBar}>
        <div className={styles.sortTitle}>排序方式</div>
        <Space wrap>
          <Button 
            size="small" 
            onClick={() => this.handleSort('number', 'asc')}
            className={styles.sortButton}
          >
            号码升序
          </Button>
          <Button 
            size="small" 
            onClick={() => this.handleSort('number', 'desc')}
            className={styles.sortButton}
          >
            号码降序
          </Button>
          <Button 
            size="small" 
            onClick={() => this.handleSort('name', 'asc')}
            className={styles.sortButton}
          >
            姓名A-Z
          </Button>
          <Button 
            size="small" 
            onClick={() => this.handleSort('name', 'desc')}
            className={styles.sortButton}
          >
            姓名Z-A
          </Button>
          <Button 
            size="small" 
            onClick={this.handleClearSort}
            className={styles.clearSortButton}
          >
            清除排序
          </Button>
        </Space>
      </div>
    );
  };

  renderEmpty = () => {
    const { searchTerm, sortType } = this.props;
    
    return (
      <Empty
        className={styles.empty}
        image={<SearchOutline style={{ fontSize: 64, color: '#999' }} />}
        description={
          <div className={styles.emptyContent}>
            <div className={styles.emptyText}>
              {searchTerm ? '没有找到相关球员' : 
               sortType ? '没有符合条件的球员' : '暂无球员数据'}
            </div>
            {(searchTerm || sortType) && (
              <Space>
                {searchTerm && (
                  <Button 
                    size="small" 
                    onClick={this.handleClearSearch}
                    className={styles.clearButton}
                  >
                    清空搜索
                  </Button>
                )}
                {sortType && (
                  <Button 
                    size="small" 
                    onClick={this.handleClearSort}
                    className={styles.clearButton}
                  >
                    清除排序
                  </Button>
                )}
              </Space>
            )}
          </div>
        }
      />
    );
  };

  renderError = () => {
    return (
      <div className={styles.errorContainer}>
        <Empty
          image={<ExclamationCircleOutline style={{ fontSize: 64, color: '#ff3141' }} />}
          description="加载失败，请重试"
        />
        <Button 
          color="primary" 
          onClick={this.handleRetry}
          className={styles.retryButton}
        >
          重新加载
        </Button>
      </div>
    );
  };

  render() {
    const { 
      filteredPlayers, 
      loading, 
      error, 
      searchTerm
    } = this.props;
    const { refreshing, showSort } = this.state;

    if (error) {
      return (
        <div className={styles.container}>
          {this.renderError()}
        </div>
      );
    }

    return (
      <div className={styles.container}>
        <div className={styles.header}>
          <SearchBar
            placeholder="搜索球员姓名、号码"
            value={searchTerm}
            onChange={this.handleSearch}
            onClear={this.handleClearSearch}
            className={styles.searchBar}
            showCancelButton
          />
          
          <Button 
            size="small" 
            onClick={() => this.setState({ showSort: !showSort })}
            className={styles.sortToggle}
          >
            <UnorderedListOutline />
            排序
          </Button>
        </div>

        {this.renderSortBar()}

        <div className={styles.content}>
          <PullToRefresh
            onRefresh={this.handleRefresh}
            refreshing={refreshing}
          >
            <List className={styles.playerList}>
              {filteredPlayers.length > 0 ? (
                filteredPlayers.map(player => this.renderPlayerItem(player))
              ) : (
                <List.Item>
                  {this.renderEmpty()}
                </List.Item>
              )}
            </List>
          </PullToRefresh>
        </div>

        {loading && !refreshing && (
          <div className={styles.loading}>
            <div className={styles.loadingText}>加载中...</div>
          </div>
        )}
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  players: state.players.players,
  filteredPlayers: state.players.filteredPlayers,
  searchTerm: state.players.searchTerm,
  sortType: state.players.sortType,
  sortOrder: state.players.sortOrder,
  loading: state.players.loading,
  error: state.players.error,
});

export default connect(mapStateToProps)(PlayerList);
